// src/pages/Products.js
import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, Upload, message } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Option } = Select;

const Products = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [currentProductId, setCurrentProductId] = useState(null);

  
  const fetchProducts = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/products');
      console.log(response, 'product')
      setProducts(response.data.products);
    } catch (error) {
      message.error('获取商品列表失败');
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    fetchProducts();
  }, []);


  const handleAddProduct = () => {
    form.resetFields();
    setIsEditing(false);
    setCurrentProductId(null);
    setModalVisible(true);
  };

  const handleEditProduct = (record) => {
    form.setFieldsValue(record);
    setIsEditing(true);
    setCurrentProductId(record.id);
    setModalVisible(true);
  };

  const handleDeleteProduct = async (id) => {
    try {
      await axios.delete(`/api/products/${id}`);
      message.success('删除成功');
      fetchProducts();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (isEditing) {
        await axios.put(`/api/products/${currentProductId}`, values);
        message.success('更新成功');
      } else {
        await axios.post('/api/products', values);
        message.success('创建成功');
      }
      form.resetFields();
      setModalVisible(false);
      fetchProducts();
    } catch (errorInfo) {
      console.log('Validation failed:', errorInfo);
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '分类', dataIndex: 'category', key: 'category' },
    { title: '价格', dataIndex: 'price', key: 'price' },
    { title: '库存', dataIndex: 'stock', key: 'stock' },
    { title: '图片', dataIndex: 'image', key: 'image', render: (text) => <img src={text} alt="产品" style={{ maxWidth: 100 }} /> },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <span>
          <Button size="small" onClick={() => handleEditProduct(record)}>
            编辑
          </Button>
          <Button size="small" danger onClick={() => handleDeleteProduct(record.id)} style={{ marginLeft: 8 }}>
            删除
          </Button>
        </span>
      ),
    },
  ];

  return (
    <div>
      <Button type="primary" onClick={handleAddProduct} style={{ marginBottom: 16 }}>
        <PlusOutlined /> 添加商品
      </Button>
      
      <Table 
        dataSource={products} 
        columns={columns} 
        loading={loading} 
        rowKey="id" 
      />

      <Modal
        title={isEditing ? '编辑商品' : '添加商品'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleSubmit}
      >
        <Form
          form={form}
          layout="vertical"
          name="productForm"
        >
          <Form.Item
            name="name"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input />
          </Form.Item>
          
          <Form.Item
            name="category"
            label="商品分类"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select placeholder="请选择分类">
              <Option value="electronics">电子产品</Option>
              <Option value="clothing">服装</Option>
              <Option value="books">图书</Option>
              <Option value="food">食品</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="price"
            label="价格"
            rules={[{ required: true, message: '请输入价格' }, { type: 'number', min: 0 }]}
          >
            <Input type="number" />
          </Form.Item>
          
          <Form.Item
            name="stock"
            label="库存"
            rules={[{ required: true, message: '请输入库存' }, { type: 'number', min: 0, integer: true,message: '必须是数字类型' }]}
          >
            <Input type='number' />
          </Form.Item>
          
          <Form.Item
            name="image"
            label="商品图片"
            rules={[{ required: true, message: '请上传图片' }]}
          >
            <Upload
              name="image"
              listType="picture"
              maxCount={1}
              beforeUpload={() => false} // 阻止自动上传
            >
              <Button icon={<UploadOutlined />}>点击上传</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Products;